<template>
  <div class="app-container question-new">
    <el-card>
      <div slot="header">{{$route.query.id ? '试题修改':'试题录入'}}</div>
      <el-form label-width="120px"
               :model="form"
               :rules="rules"
               ref="form">
        <!-- 学科 -->
        <el-form-item label="学科："
                      prop="subjectID">
          <el-select placeholder="请选择"
                     style="width: 300px;"
                     v-model="form.subjectID"
                     @change="changeSubject">
            <el-option v-for="item in subjectOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录："
                      prop="catalogID">
          <el-select placeholder="请选择"
                     style="width: 300px;"
                     v-model="form.catalogID">
            <el-option v-for="item in catalogOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>

          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业："
                      prop="enterpriseID">
          <el-select placeholder="请选择"
                     style="width: 300px;"
                     v-model="form.enterpriseID">
            <el-option v-for="item in enterpriseOptions"
                       :key="item.id"
                       :label="item.company"
                       :value="item.id"></el-option>

          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市："
                      prop="city">
          <el-select placeholder="请选择"
                     style="width:148px"
                     v-model="form.province"
                     @change="getAreaOptions">
            <el-option v-for="item in cityOptions"
                       :key="item"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
          <el-select style="margin-left: 5px; width:148px"
                     placeholder="请选择"
                     v-model="form.city">
            <el-option v-for="item in areaOptions"
                       :key="item"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向  -->
        <el-form-item label="方向："
                      prop="direction">
          <el-select placeholder="请选择"
                     style="width: 300px;"
                     v-model="form.direction">
            <el-option v-for="item in directionOptions"
                       :key="item"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 单选框 -->
        <el-form-item label="题型："
                      prop="questionType">
          <el-radio-group v-model="form.questionType"
                          @change="changeRadio({})">
            <el-radio v-for="item in questionType"
                      :key="item.value"
                      :label="item.value + '' ">{{item.label}}</el-radio>

          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度："
                      prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio v-for="item in difficulty"
                      :key="item.value"
                      :label="item.value + ''">{{item.label}}</el-radio>

          </el-radio-group>
        </el-form-item>
        <!-- 题干 富文本 -->
        <el-form-item label="题干："
                      prop="question">
          <quill-editor :options="editorOptions"
                        v-model="form.question"></quill-editor>
        </el-form-item>
        <!-- 选项 上传图片-->
        <el-form-item label="选项:"
                      prop="options"
                      v-if="form.questionType !== '3' ">
          <div class="option_item"
               v-for="item in form.options"
               :key="item.code">
            <el-radio style="margin-right:0"
                      v-model="item.isRight"
                      :label="true"
                      @change="changeRadio(item)"
                      v-if="form.questionType === '1'">{{item.code}}：</el-radio>
            <el-checkbox style="margin-right:0"
                         v-model="item.isRight"
                         :label="true"
                         v-if="form.questionType ==='2'">{{item.code}}：</el-checkbox>
            <el-input style="width:240px"
                      v-model="item.title"></el-input>
            <el-upload style="margin-left:4px"
                       class="avatar-uploader"
                       action="https://jsonplaceholder.typicode.com/posts/"
                       :show-file-list="false"
                       :on-success="(res, file)=>{uploadSuccess(item, res, file)}"
                       :headers="{'Authorization':'Bearer '+ token}">
              <img :src="item.img"
                   class="avatar"
                   v-if="item.img">
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </div>
          <!-- 添加按钮 -->
          <el-button type="danger"
                     size="small"
                     :disabled="form.questionType !=='2'"
                     @click="addOption">+增加选项与答案</el-button>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频:"
                      prop="videoURL">
          <el-input style="width:400px"
                    v-model="form.videoURL"></el-input>
        </el-form-item>
        <!-- 答案解析  富文本 -->
        <el-form-item label="答案解析："
                      prop="question">
          <quill-editor :options="editorOptions"
                        v-model="form.answer"></quill-editor>
        </el-form-item>
        <!--题目备注 文本域  -->
        <el-form-item label="题目备注："
                      prop="remarks">
          <el-input type="textarea"
                    style="width:400px"
                    :rows="4"
                    v-model="form.remarks"></el-input>
        </el-form-item>
        <!--  试题标签 输入框 -->
        <el-form-item label="试题标签：">
          <el-select style="width:400px"
                     multiple
                     filterable
                     allow-create
                     default-first-option
                     placeholder="请选择试题标签"
                     v-model="form.tags">
            <el-option v-for="item in tagsOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary"
                     v-if="!$route.query.id"
                     @click="add">确认提交</el-button>
          <el-button type="success"
                     v-else
                     @click="edit">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 富文本编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import { simple as getSubjectOptions } from '@/api/hmmm/subjects' // 学科列表
import { simple as getCatalogOptions } from '@/api/hmmm/directorys' // 目录简单列表
import { simple as getTagOptions } from '@/api/hmmm/tags' // 标签简单列表
import { list as getCompanyOptions } from '@/api/hmmm/companys' // 企业管理
import { provinces as getCityOptions, citys as getAreaOptions } from '@/api/hmmm/citys' // 城市
import { direction, questionType, difficulty } from '@/api/hmmm/constants' // 方向,题型,难度
import { getToken } from '@/utils/auth'
import { add, update, detail } from '@/api/hmmm/questions' // 添加 -修改
export default {
  name: 'QuestionsNew',
  components: {
    quillEditor
  },
  data () {
    return {
      // 富文本
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ]
        }
      },
      // 试题对象
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 市区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干 富文本
        tags: '', // 标签
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        // textField: ''// 文本域
        videoURL: '', // 解析视屏
        remarks: '' // 备注
      },
      // 校验规则
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        videoURL: [{ required: true, message: '请输入解析视屏', trigger: 'change' }],
        remarks: [{ required: true, message: '请输入备注', trigger: 'change' }]
      },
      // 学科列表
      subjectOptions: [],
      // 目录
      catalogOptions: [],
      // 企业
      enterpriseOptions: [],
      // // 城市
      cityOptions: getCityOptions(),
      // // 地区
      areaOptions: [],
      // // 方向
      directionOptions: direction,
      // // 题型 单选框
      questionType,
      // // 难度 单选框
      difficulty,
      // // 标签
      tagsOptions: '',
      token: getToken()
    }
  },
  created () {
    this.getSubjectOptions() // 学科列表渲染
    this.getCompanyOptions() // 企业管理
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  methods: {
    // 获取题目的列表 进行数据回显
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.form = data
      // 目录
      const res = await getCatalogOptions()
      this.catalogOptions = res.data
      // 标签
      const res2 = await getTagOptions()
      this.tagsOptions = res2.data
    },
    // 添加选项  // 下例返回字符串 "ABC"： String.fromCharCode(65,66,67)  String.fromCharCode(65 + index)
    addOption () {
      this.form.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.form.options.length),
        title: '',
        img: ''
      })
    },
    // 上传 uploadSuccess:不带括号接收默认参数  uploadSuccess:带了括接收自己传入参数
    uploadSuccess (item, res, file) {
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      item, img = URL.createObjectURL(file.raw)
    },
    // 选择了题型 - 单选框
    changeRadio (item) {
      // 1.清空所有的选中
      this.form.options.forEach(item => { item.isRight = false })
      // 2.自己选中
      item.isRight = true
    },
    // 地区
    getAreaOptions (cityName) {
      this.form.city = ''
      this.areaOptions = getAreaOptions(cityName)
    },
    // 企业
    async getCompanyOptions () {
      const res = await getCompanyOptions({ pagesize: 10000 })
      // console.log(res) // id 选项值  company 选项文字
      this.enterpriseOptions = res.data.items
    },
    // 学科简单列表
    async getSubjectOptions () {
      const res = await getSubjectOptions()
      this.subjectOptions = res.data
    },
    // 改变学科
    async changeSubject () {
      console.log('---改变了学科')
      // 目录
      const res = await getCatalogOptions()
      this.catalogOptions = res.data
      // 标签
      const res2 = await getTagOptions()
      this.tagsOptions = res2.data
    },
    // 确认提交 校验
    async add () {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      console.log('--确认提交')
      // 处理form.tags 的格式要转成字符串
      const data = { ...this.form }
      data.tags = this.form.tags.join(',')
      await add(data)
      this.$message.success('添加成功')
      this.$router.push('/questions/list') // 跳转基础题库
    },
    // 修改
    async edit () {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.$route.query.id) {
        const data = { ...this.form }
        console.log(this.form)
        data.tags = this.form.tags.join(',')
        await update(data)
        this.$message.success('修改成功成功')
        this.$router.push('/questions/list') // 跳转基础题库
      }
    }
  }

}
</script>

<style scoped lang='scss'>
// 现在仅在当前组件下生效，让样式的作用更深
.question-new ::v-deep .ql-editor {
  height: 200px;
}
.question-new ::v-deep .ql-toolbar.ql-snow {
  padding: 0 8px;
}
.option_item {
  padding-bottom: 20px;
}
.avatar-uploader {
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}
.question-new ::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.question-new ::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.question-new ::v-deep .avatar-uploader i {
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
  overflow: hidden;
}
</style>
